<!--
 * @Author: whr2349 378237242@qq.com
 * @Date: 2025-08-14 11:15:56
 * @LastEditors: whr2349 378237242@qq.com
 * @LastEditTime: 2025-08-19 09:22:46
 * @FilePath: \study-openlayers\src\pages\element-plus\calendar.vue
 * @Description: 日历组件，测试示例

 * 
 * Copyright (c) 2025 by ${git_name_email}, All Rights Reserved. 
-->
<template>
  <div>
    <div>日报</div>
    <el-calendar v-model="value">
      <template #date-cell="{ data }">
        <p>
          {{ data.day.split("-").slice(2).join("") }}
          <div>
             {{ dateFormatDayjs(data.date) }}
           <!-- 展示当日的统计数据 -->
            <el-tag >{{ getGroupDataLength(dateFormatDayjs(data.date)) }}</el-tag>
          </div>
         
        </p>
      </template>
    </el-calendar>

    <div>月报</div>
    <div class="month-calendar-container">
      <div class="month-calendar-header">
        <el-button @click="scrollToCurrentMonth" type="primary" size="small">当前月份</el-button>
        <span class="current-year">{{ currentDisplayYear }}年</span>
      </div>
      <div ref="monthScrollContainer" class="month-scroll-container" @scroll="handleScroll">
        <div ref="monthContent" class="month-content">
          <div v-for="year in displayYears" :key="year" class="year-block">
            <div class="year-title">{{ year }}年</div>
            <div class="months-grid">
              <div v-for="month in 12" :key="`${year}-${month}`" 
                   :class="[`month-item`, isCurrentMonth(year, month) ? 'current-month' : '']" 
                   @click="selectMonth(year, month)">
                <div class="month-name">{{ getMonthName(month) }}</div>
                <div class="month-count">
                  <el-tag size="small">{{ getGroupDataLengthByMonth(year, month) }}</el-tag>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { dayjs } from 'element-plus'

const value = ref(new Date());
// 月报相关数据
const currentYear = ref(dayjs().year());
const currentMonth = ref(dayjs().month() + 1); // dayjs的月份是0-11
const displayYears = ref([]);
const monthScrollContainer = ref(null);
const monthContent = ref(null);
const currentDisplayYear = ref(currentYear.value);

// 初始化显示年份范围
onMounted(() => {
  // 初始显示当前年份前后各3年，总共7年的范围
  const initialYears = [];
  for (let i = -3; i <= 3; i++) {
    const year = currentYear.value + i;
    if (year >= 2015) { // 确保不显示2015年之前的年份
      initialYears.push(year);
    }
  }
  updateDisplayYears(initialYears);
  
  // 延迟滚动到当前月份，确保DOM已渲染
  setTimeout(() => {
    scrollToCurrentMonth();
  }, 100);
});

// 更新显示的年份范围，确保平滑滚动
function updateDisplayYears(yearsArray) {
  // 只有当年份数组发生变化时才更新，避免不必要的重新渲染
  if (yearsArray.length !== displayYears.value.length || !yearsArray.every((year, index) => year === displayYears.value[index])) {
    displayYears.value = [...yearsArray];
    currentDisplayYear.value = yearsArray[Math.floor(yearsArray.length / 2)]; // 更新当前显示年份为中间年份
  }
}

// 处理滚动事件，实现无限滚动
function handleScroll() {
  const container = monthScrollContainer.value;
  const content = monthContent.value;
  
  if (!container || !content) return;
  
  const scrollTop = container.scrollTop;
  const scrollHeight = content.offsetHeight;
  const containerHeight = container.offsetHeight;
  const yearBlockHeight = 180; // 估算每年块的高度，用于更精确的滚动位置调整
  
  // 避免在短时间内频繁触发滚动更新
  if (handleScroll.lastUpdate && Date.now() - handleScroll.lastUpdate < 100) {
    return;
  }
  handleScroll.lastUpdate = Date.now();
  
  // 滚动到顶部附近，加载前面的年份
  if (scrollTop < 200 && displayYears.value[0] > 2015) {
    // 直接在现有年份列表前面添加一个新年份
    const newYear = displayYears.value[0] - 1;
    const updatedYears = [newYear, ...displayYears.value];
    
    // 限制显示的年份总数为7年
    if (updatedYears.length > 7) {
      updatedYears.pop(); // 移除最旧的年份
    }
    
    updateDisplayYears(updatedYears);
    
    // 使用requestAnimationFrame确保DOM更新后再调整滚动位置
    requestAnimationFrame(() => {
      if (container) {
        // 精确调整滚动位置，使视口内容保持不变
        container.scrollTop = scrollTop + yearBlockHeight;
      }
    });
  }
  
  // 滚动到底部附近，加载后面的年份
  if (scrollTop > scrollHeight - containerHeight - 200) {
    // 直接在现有年份列表后面添加一个新年份
    const newYear = displayYears.value[displayYears.value.length - 1] + 1;
    const updatedYears = [...displayYears.value, newYear];
    
    // 限制显示的年份总数为7年
    if (updatedYears.length > 7) {
      updatedYears.shift(); // 移除最早的年份
    }
    
    updateDisplayYears(updatedYears);
    
    // 使用requestAnimationFrame确保DOM更新后再调整滚动位置
    requestAnimationFrame(() => {
      if (container) {
        // 精确调整滚动位置，使视口内容保持不变
        container.scrollTop = scrollTop - yearBlockHeight;
      }
    });
  }
}
// 添加静态属性用于节流
handleScroll.lastUpdate = 0;

// 滚动到当前月份
function scrollToCurrentMonth() {
  const container = monthScrollContainer.value;
  if (!container) return;
  
  // 确保当前年份在显示范围内
  if (!displayYears.value.includes(currentYear.value)) {
    // 创建一个以当前年份为中心的新年份列表
    const yearsAroundCurrent = [];
    for (let i = -3; i <= 3; i++) {
      const year = currentYear.value + i;
      if (year >= 2015) {
        yearsAroundCurrent.push(year);
      }
    }
    updateDisplayYears(yearsAroundCurrent);
  }
  
  // 延迟一下，确保年份已更新
  setTimeout(() => {
    const currentMonthEl = document.querySelector('.month-item.current-month');
    if (currentMonthEl) {
      const containerRect = container.getBoundingClientRect();
      const monthRect = currentMonthEl.getBoundingClientRect();
      container.scrollTop += (monthRect.top - containerRect.top) - containerRect.height / 2 + monthRect.height / 2;
    }
  }, 100);
}

// 检查是否是当前月份
function isCurrentMonth(year, month) {
  return year === currentYear.value && month === currentMonth.value;
}

// 选择月份
function selectMonth(year, month) {
  // 这里可以添加选择月份后的逻辑
  console.log(`选择了 ${year}年${month}月`);
}

// 获取月份名称
function getMonthName(month) {
  return `${month}月`;
}

// 按照年月统计数据
function getGroupDataLengthByMonth(year, month) {
  const monthStr = month.toString().padStart(2, '0');
  const key = `${year}-${monthStr}`;
  
  // 统计tableData中SBSJ字段包含该年月的数据数量
  let count = 0;
  tableData.value.forEach(item => {
    if (item.SBSJ && item.SBSJ.startsWith(key)) {
      count++;
    }
  });
  
  return count;
}
// 按照tableData的SBSJ上报月份统计数据，相同月份的实例数据合并
function getGroupDataByMonth() {
  const groupData = {};
  tableData.value.forEach(item => {
    const month = item.SBSJ.slice(0, 7);
    if (!groupData[month]) {
      groupData[month] = [];
    }
    groupData[month].push(item);
  });
  return groupData;
}

// tableData 是一个示例数据
const tableData = ref([
  {
    BSM: "55508b03-e11e-4b99-80c3-e34e78fc2eur",
    XZQHDM: "321102",
    SBSJ: "2025-07-18T00:00:00",
    YHLX: 7,
    YHMC: "梦溪广场东南角",
    YHDDZ: "梦溪广场东南角",
    YHMS: "",
    YHXCWJ: [],
    SBRY: null,
    SBRLXDH: null,
    YHCZDW: null,
    CZFZR: null,
    CZFZRLXDH: null,
    YHSLSJ: "2017-02-17T00:00:00",
    YHCZJS: null,
    YHCZBG: null,
    CZWCSJ: "2017-02-17T00:00:00",
    BZ: null,
    KJXX: "MULTIPOLYGON (((119.46051035700009 32.203501268000025, 119.46053728300001 32.20350322200005, 119.46054017400002 32.203474422000056, 119.4605132480001 32.20347246800003, 119.46051035700009 32.203501268000025)))",
    SJGXLX: "RQ",
    YSKZJBZ: "e7e2bf76-dff3-4aa4-babc-37dbb23f501c",
    SJTBZT: "I",
    TBSJ: "2025-05-22T13:44:14.937429",
    YHHCSJ: null,
    YHHCR: null,
    YHHCDW: null,
    HCBZ: null,
    CZWCWJ: [],
    TSRY: "",
    TSRLXDH: "",
    BTSDW: "",
    BTSFZR: "",
    BTSFZRLXDH: "",
    TSSJ: "2017-02-17T00:00:00",
    TSDW: null,
    SYXGXCZ: "钢管",
    SYXGXCD: 25,
    SYXQYMJ: 1,
    SYXSD: 0.5,
    JHFXYJSM: null,
  },
  {
    BSM: "55508b03-e11e-4b99-80c3-e34e6eac2eur",
    XZQHDM: "321102",
    SBSJ: "2025-08-18T00:00:00",
    YHLX: 7,
    YHMC: "梦溪广场东南角",
    YHDDZ: "梦溪广场东南角",
    YHMS: "",
    YHXCWJ: [],
    SBRY: null,
    SBRLXDH: null,
    YHCZDW: null,
    CZFZR: null,
    CZFZRLXDH: null,
    YHSLSJ: "2017-02-17T00:00:00",
    YHCZJS: null,
    YHCZBG: null,
    CZWCSJ: "2017-02-17T00:00:00",
    BZ: null,
    KJXX: "MULTIPOLYGON (((119.46051035700009 32.203501268000025, 119.46053728300001 32.20350322200005, 119.46054017400002 32.203474422000056, 119.4605132480001 32.20347246800003, 119.46051035700009 32.203501268000025)))",
    SJGXLX: "RQ",
    YSKZJBZ: "e7e2bf76-dff3-4aa4-babc-37dbb23f501c",
    SJTBZT: "I",
    TBSJ: "2025-05-22T13:44:14.937429",
    YHHCSJ: null,
    YHHCR: null,
    YHHCDW: null,
    HCBZ: null,
    CZWCWJ: [],
    TSRY: "",
    TSRLXDH: "",
    BTSDW: "",
    BTSFZR: "",
    BTSFZRLXDH: "",
    TSSJ: "2017-02-17T00:00:00",
    TSDW: null,
    SYXGXCZ: "钢管",
    SYXGXCD: 25,
    SYXQYMJ: 1,
    SYXSD: 0.5,
    JHFXYJSM: null,
  },
  {
    BSM: "55508b03-e11e-4b99-80c3-e34e6eac2412",
    XZQHDM: "321102",
    SBSJ: "2025-08-18T00:00:00",
    YHLX: 7,
    YHMC: "梦溪广场东南角1",
    YHDDZ: "梦溪广场东南角1",
    YHMS: "",
    YHXCWJ: [],
    SBRY: null,
    SBRLXDH: null,
    YHCZDW: null,
    CZFZR: null,
    CZFZRLXDH: null,
    YHSLSJ: "2017-02-17T00:00:00",
    YHCZJS: null,
    YHCZBG: null,
    CZWCSJ: "2017-02-17T00:00:00",
    BZ: null,
    KJXX: "MULTIPOLYGON (((119.46051035700009 32.203501268000025, 119.46053728300001 32.20350322200005, 119.46054017400002 32.203474422000056, 119.4605132480001 32.20347246800003, 119.46051035700009 32.203501268000025)))",
    SJGXLX: "RQ",
    YSKZJBZ: "e7e2bf76-dff3-4aa4-babc-37dbb23f501c",
    SJTBZT: "I",
    TBSJ: "2025-05-22T13:44:14.937429",
    YHHCSJ: null,
    YHHCR: null,
    YHHCDW: null,
    HCBZ: null,
    CZWCWJ: [],
    TSRY: "",
    TSRLXDH: "",
    BTSDW: "",
    BTSFZR: "",
    BTSFZRLXDH: "",
    TSSJ: "2017-02-17T00:00:00",
    TSDW: null,
    SYXGXCZ: "钢管",
    SYXGXCD: 25,
    SYXQYMJ: 1,
    SYXSD: 0.5,
    JHFXYJSM: null,
  },
  {
    BSM: "55508b03-e11e-4b99-80c3-e58e6eac2412",
    XZQHDM: "321102",
    SBSJ: "2025-08-17T00:00:00",
    YHLX: 7,
    YHMC: "梦溪广场东南角1",
    YHDDZ: "梦溪广场东南角1",
    YHMS: "",
    YHXCWJ: [],
    SBRY: null,
    SBRLXDH: null,
    YHCZDW: null,
    CZFZR: null,
    CZFZRLXDH: null,
    YHSLSJ: "2017-02-17T00:00:00",
    YHCZJS: null,
    YHCZBG: null,
    CZWCSJ: "2017-02-17T00:00:00",
    BZ: null,
    KJXX: "MULTIPOLYGON (((119.46051035700009 32.203501268000025, 119.46053728300001 32.20350322200005, 119.46054017400002 32.203474422000056, 119.4605132480001 32.20347246800003, 119.46051035700009 32.203501268000025)))",
    SJGXLX: "RQ",
    YSKZJBZ: "e7e2bf76-dff3-4aa4-babc-37dbb23f501c",
    SJTBZT: "I",
    TBSJ: "2025-05-22T13:44:14.937429",
    YHHCSJ: null,
    YHHCR: null,
    YHHCDW: null,
    HCBZ: null,
    CZWCWJ: [],
    TSRY: "",
    TSRLXDH: "",
    BTSDW: "",
    BTSFZR: "",
    BTSFZRLXDH: "",
    TSSJ: "2017-02-17T00:00:00",
    TSDW: null,
    SYXGXCZ: "钢管",
    SYXGXCD: 25,
    SYXQYMJ: 1,
    SYXSD: 0.5,
    JHFXYJSM: null,
  },
]);
// 格式化日期
const dateFormatDayjs = (date) => {
  return dayjs(date).format("YYYY-MM-DD");
};

// 按照tableData的SBSJ上报日期统计数据，相同日期的实例数据合并
const tableDataGroupByDate = () => {
  const group = {};
  tableData.value.forEach((item) => {
    const date = dateFormatDayjs(item.SBSJ);
    if (group[date]) {
      group[date].push(item);
    } else {
      group[date] = [item];
    }
  });
  return group;
};

// 分组后的数据
const groupData = tableDataGroupByDate();
const getGroupDataLength = (date) => {
  debugger;
  console.log(date);
  console.log(groupData);
  console.log(groupData[date])
  return groupData[date]? groupData[date].length : 0;

};
// console.log(tableDataGroupByDate());


</script>

<style lang="scss" scoped>
.month-calendar-container {
  margin-top: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.month-calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 16px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.current-year {
  font-size: 16px;
  font-weight: bold;
}

.month-scroll-container {
  height: 400px;
  overflow-y: auto;
  position: relative;
}

.month-content {
  padding: 16px;
}

.year-block {
  margin-bottom: 24px;
}

.year-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 12px;
  padding-left: 8px;
  border-left: 4px solid #409eff;
}

.months-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 12px;
}

.month-item {
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.month-item:hover {
  background-color: #f5f7fa;
  border-color: #c0c4cc;
}

.current-month {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.month-name {
  font-size: 16px;
  margin-bottom: 8px;
}

.month-count {
  display: flex;
  justify-content: center;
}
</style>
